using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using LambdaBuilder.Resolver;
using Catastrophe.Common.AttributeEx;
using Catastrophe.Common.FileM;
using System.Net.Http.Json;

namespace Catastrophe.CommonCore.FileM
{
    /// <summary>
    /// 文件
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class FileConfigManager<T> where T : class, new()
    {
        /// <summary>
        /// 目录
        /// </summary>
        private string Catalogue { get; set; } = "ConfigCatalogue\\";
        /// <summary>
        /// 文件地址
        /// </summary>
        public string FullName { get; set; }

        /// <summary>
        /// 文件类型
        /// </summary>
        public FileTypeEnum FileTypeEnum { get; set; }

        /// <summary>
        /// 
        /// </summary>
        public T Value { get; set; }

        public FileConfigManager(FileTypeEnum fileType, string fileName = "")
        {
            this.FileTypeEnum = fileType;
            if (string.IsNullOrWhiteSpace(fileName))
            {
                FileNameAttribute customClassAb2 = BuildAttribute.GetCustomClassAb<FileNameAttribute, T>();

                if (customClassAb2 == null)
                {
                    throw new Exception("未检测到FileNameAttribute");
                }
                this.FullName = Catalogue+ customClassAb2.Name;
            }
            else
            {
                this.FullName = Catalogue + fileName;
            }
            if (!Directory.Exists(Catalogue))
            {
                Directory.CreateDirectory(Catalogue);
            }
            if (!File.Exists(FullName))
            {
                File.Create(FullName).Close();
                Value = new T();
                Write();
            }
        }


        /// <summary>
        /// 读取
        /// </summary>
        /// <returns></returns>
        public T ReadEntity()
        {
            var value = File.ReadAllText(this.FullName);
            try
            {
                Value = Newtonsoft.Json.JsonConvert.DeserializeObject<T>(value);
            }
            catch
            {
                Value = new T();
            }
            return Value;
        }

        /// <summary>
        /// 读取
        /// </summary>
        /// <returns></returns>
        public void Write()
        {
            File.WriteAllText(FullName, Newtonsoft.Json.JsonConvert.SerializeObject(Value));
        }
    }
}
